<?php

/**
 * Created by ghostsf
 * Date: 2016/4/20
 */

namespace app\admin\controller;

use app\admin\model\Config;
use app\admin\model\Personalconfig;
use think\Controller;
use think\Db;
use think\Config as redis;

/**
 * 公共
 * Class Common
 * @package app\admin\controller
 */
class CommonController extends Controller {
	public  $redis;
    /**
     * 拦截器
     *
     * @return bool
     */
    public function _initialize() {
//session过期验证
        if (!isset($_SESSION['loginSession'])) {
            header("http/1.1", true, 389); //389 http状态码 session过期
            return false;
        }
    }


    /**
     * 发送短信
     * @param $phone
     * @param $num
     * @return mixed
     */
    public function duaxin($phone,$num){
        $body_json = array(
            'sid'=>'2010a51e49df34754c876fbe910061a4',
            'token'=>'01528a612dab2ad66f70fca870a88078',
            'appid'=>'85f7e8ae0e2d4dd6a9d619ccda794047',
            'templateid'=>'296258',
            'param'=>$num,
            'mobile'=>$phone,
            'uid'=>'',
        );
        $body = json_encode($body_json);
        $header = array(
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
        );
        $url = 'https://open.ucpaas.com/ol/sms/sendsms';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
    }


    /**
     * 获取融云token
     * @param $uid
     * @param $name
     * @param $imageurl
     * @return mixed
     */
    public function rongyun($uid=0,$name='',$imageurl=''){//echo 1;die;
        $appKey = 'n19jmcy5n8l09';
        $appSecret = 'P8BCshr6wkp5T';
        $body = "userId={$uid}&name={$name}&portraitUri={$imageurl}";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret.$nonce.$timeStamp);
        $header = array(
            'App-Key:'.$appKey,
            'Nonce:'.$nonce,
            'Timestamp:'.$timeStamp,
            'Signature:'.$sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/user/getToken.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
//    var_dump($res) ;
    }

    public function uploadFile($tmp,$name,$size)
    {
        if($size > 2048*1024){
            return array('status'=>0,'msg'=>"图片不得超过2M！");
        }
        $imgarray = array('jpg','jpeg','png');
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        if($tmp){
            //=======重命名=====
            $rand = date('YmdHis').rand(100000,999999);
            $exe = explode('.',$name);
            $exe = end($exe);
            if(!in_array($exe,$imgarray)){
                return array('status'=>0,'msg'=>'图片格式不支持');
            }
            $newName = $rand . '.' .$exe;
            //=======================
            if(move_uploaded_file($tmp,"{$dir}/static/image/place/{$newName}")){
                $imgUrl = "{$url}/static/image/place/{$newName}";
                return array('status'=>200,'msg'=>$imgUrl);
            }else{
                return array('status'=>0,'msg'=>'图片保存失败');
            }
        }else{
            return array('status'=>0,'msg'=>"上传一张图！");
        }
    }

    /**
     * 验证唯一性：异地登陆
     * @param $uid
     * @param $time
     * @param $value
     * @param $reqKey
     * @return bool
     */
    public  function checkAll($uid,$time,$value,$reqKey){//$uid,$time,$value
        header("Access-Control-Allow-Origin:*");
        if($uid == 0){
            return true;
        }else{
            $user = Db::table('ew_u_user')->where('user_id',$uid)->find();
            if($user['user_status'] != 1){//禁用
                return false;
            }
            $token = $user['user_token'];
            $appId = "A6060432236270";
            $appkey = "F591B37E-1C61-01C7-57C6-8B2F6D59DCD9";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey){
                return false;
            }else{
                return true;
            }
        }
    }





	
	/** redis连接
     * @return bool
     */

    public function redis()
    {
        $options=redis::get('database');
        $redisHost=array_key_exists("redisHost",$options)?$options['redisHost']:"127.0.0.1";
        $redisPort=array_key_exists("redisPort",$options)?$options['redisPort']:6379;
        $redisAuth=array_key_exists("redisAuth",$options)?$options['redisAuth']:'';
        $redisHost=$redisHost==null?"127.0.0.1":$redisHost;
        $redisPort=$redisPort==null? 6379:$redisPort;
        if(extension_loaded("redis")){
            $redis= new \redis();
            if($redis->connect($redisHost,$redisPort)){
                if($redisAuth!=null){
                    $redis->auth($redisAuth);
                    if(false==$redis->set('ce',1)){
                        return false;
                    }
                }
               $this->redis=$redis;
                return true;
            }else{
                  return false;
                die;
                $tishi="redis连接失败原因IP地址连接有误";
                die($tishi);
            }

        }else{
            return false;
        }
    }

    /**
     * 全局设置
     * @param array $arr
     */
    public function setGlobalSettings($arr = []) {
        foreach ($arr as $name) {
            $config = Config::get(array("name" => $name));
            $this->assign($name, $config->value);
        }
    }

    /**
     * 个性设置
     * @param array $arr
     */
    public function setPersonalSettings($arr = []) {
        $loginSession = session('loginSession');
        $userid = $loginSession['id'];
        foreach ($arr as $name) {
            $personalConfig = Personalconfig::get(array("name" => $name, "userid" => $userid));
            if ($personalConfig) {
                $this->assign($name, $personalConfig->value);
            } else {
                $this->setGlobalSettings([$name]);
            }
        }
    }

    /**
     * 根据校区id区分数据显示
     */
    public function getDataByCampusid($arr = []) {
//为空是用来判断添加数据时要不要传参
//$str是专门用于获取数据（其他是campusid 校区管理是id） 针对校区管理 除了校区管理  其他功能不用传
        foreach ($arr as $key => $value) {
            if ($key == 'page') {
                unset($arr[$key]);
            } else if ($key == 'rows') {
                unset($arr[$key]);
            } else if ($value == '') {
                unset($arr[$key]);
            } else {
                $arr[$key] = array('like', '%' . $value . '%');
            }
        }

        return $arr;
    }


    /**
     * 压缩图片
     * @param $imgsrc:原图片地址（完整的图片路径）
     * @param $imgdst:压缩后的图片地址，也是完整的
     */
    function image_png_size_add($imgsrc,$imgdst){
        list($width,$height,$type)=getimagesize($imgsrc);
        switch($type){
            case 1:
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image = imagecreatefromjpeg($imgsrc);
                imagejpeg($image, $imgdst,70);
                imagedestroy($image);
                break;
            case 3:
                header('Content-Type:image/png');
                $image = imagecreatefrompng($imgsrc);
                imagejpeg($image, $imgdst,70);
                imagedestroy($image);
                break;
        }
    }

    /**
     * 根据经纬度算出两地的距离
     * @param $lat1
     * @param $lng1
     * @param $lat2
     * @param $lng2
     * @return int
     */
    function getDistance($lat1, $lng1, $lat2, $lng2){
        //将角度转为狐度

        $radLat1=deg2rad($lat1);//deg2rad()函数将角度转换为弧度

        $radLat2=deg2rad($lat2);

        $radLng1=deg2rad($lng1);

        $radLng2=deg2rad($lng2);

        $a=$radLat1-$radLat2;

        $b=$radLng1-$radLng2;

        $s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137;

        $res = round($s*1000);
        if($res < 1000){
            return $res . 'm';
        }else{
            return round($res/1000,2) . 'km';
        }

    }


    /**
     * 筛选搜索条件不是like是=
     */
    public function searchNotLike($searchPath=[],$postArr=[],$one='',$two='',$three='') {
        if (isset($searchPath[$one]) && $one != '') {
            unset($searchPath[$one]);
            $searchPath[$one] = $postArr[$one];
        }
        if (isset($searchPath[$two]) && $two != '') {
            unset($searchPath[$two]);
            $searchPath[$two] = $postArr[$two];
        }
        if (isset($searchPath[$three]) && $three != '') {
            unset($searchPath[$three]);
            $searchPath[$three] = $postArr[$three];
        }
        return $searchPath;
    }

    /**
     * +----------------------------------------------------------
     * Export Excel | 2016.09.14
     * Author:ghostsf <ghostsf@163.com>
     * +----------------------------------------------------------
     * @param $expTitle     string File name
     * +----------------------------------------------------------
     * @param $expCellName  array  Column name
     * +----------------------------------------------------------
     * @param $expTableData array  Table data
     * +----------------------------------------------------------
     */
    public function exportExcel($expTitle, $expCellName, $expTableData) {
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle); //文件表名称
        $fileName = $xlsTitle . date('_YmdHis'); //文件名称
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        vendor("phpoffice.phpexcel.Classes.PHPExcel");
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
//$objPHPExcel->getActiveSheet()->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
//$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . '  Export time:' . date('Y-m-d H:i:s'));
        $objPHPExcel->getDefaultStyle()->getFont()->setName('微软雅黑');
        $objPHPExcel->getDefaultStyle()->getFont()->setSize(12);
        $objPHPExcel->getActiveSheet()->getStyle('1')->applyFromArray(
                array(
                    'font' => array(
                        'bold' => true
                    )
                )
        );
        for ($i = 0; $i < $cellNum; $i++) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '1', $expCellName[$i][1]);
            $objPHPExcel->getActiveSheet()->getColumnDimension($cellName[$i])->setAutoSize(true);
        }
// Miscellaneous glyphs, UTF-8
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {
                $objPHPExcel->getActiveSheet()->setCellValue($cellName[$j] . ($i + 2), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls"); //attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * +----------------------------------------------------------
     * Import Excel | 2016.0914
     * Author:ghostsf <ghostsf@163.com>
     * +----------------------------------------------------------
     * @param  $file   upload file $_FILES
     * +----------------------------------------------------------
     * @return array   array("error","message")
     * +----------------------------------------------------------
     */
    public function read($filename,$encode='utf-8')
   {
          vendor("phpoffice.phpexcel.Classes.PHPExcel.IOFactory");
          $objReader = \PHPExcel_IOFactory::createReader('Excel5');

          $objReader->setReadDataOnly(true);

          $objPHPExcel = $objReader->load($filename);

          $objWorksheet = $objPHPExcel->getActiveSheet();

         $highestRow = $objWorksheet->getHighestRow();
         $highestColumn = $objWorksheet->getHighestColumn();
         $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
         $excelData = array();
             for ($row = 1; $row <= $highestRow; $row++) {
             for ($col = 0; $col < $highestColumnIndex; $col++) {
                 $excelData[$row][] =(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
           }
         }
      
        return $excelData;

    }

}
